package com.stellar.core.sender.impl;

import com.stellar.config.properties.AuthEmailProperties;
import com.stellar.web.core.exception.EmailSendException;
import com.stellar.core.sender.EmailCodeSender;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
@RequiredArgsConstructor
public class EmailService implements EmailCodeSender {

    private final JavaMailSender mailSender;

    private final AuthEmailProperties authEmailProperties;

    @Value("${spring.mail.username}")
    private String emailUsername;

    @Async
    public void send(String toEmail, String code) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            // 发件人显示名称
            String from = String.format("%s <%s>",
                    authEmailProperties.getFromName(),
                    emailUsername
            );

            // 替换模板占位符
            String content = authEmailProperties.getTemplate()
                    .replace("{code}", code)
                    .replace("{appName}", authEmailProperties.getAppName());

            String subject = authEmailProperties.getSubject()
                    .replace("{appName}", authEmailProperties.getAppName());

            helper.setFrom(from);
            helper.setTo(toEmail);
            helper.setSubject(subject);
            helper.setText(content, true);

            mailSender.send(message);
        } catch (MessagingException e) {
            throw new EmailSendException("邮件发送失败: " + e.getMessage());
        }
    }
}

